using Microsoft.AspNetCore.Mvc;
using WebRtcProject.Models.Messages;
using WebRtcProject.Services;

namespace WebRtcProject.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class MessagingController : ControllerBase
    {
        private readonly IRabbitMQService _rabbitMQService;
        private readonly ILogger<MessagingController> _logger;

        public MessagingController(IRabbitMQService rabbitMQService, ILogger<MessagingController> logger)
        {
            _rabbitMQService = rabbitMQService;
            _logger = logger;
        }

        /// <summary>
        /// 获取RabbitMQ连接状态
        /// </summary>
        [HttpGet("status")]
        public async Task<ActionResult> GetStatus()
        {
            try
            {
                var isConnected = await _rabbitMQService.IsConnectedAsync();
                var isHealthy = await _rabbitMQService.HealthCheckAsync();

                return Ok(new
                {
                    connected = isConnected,
                    healthy = isHealthy,
                    timestamp = DateTime.UtcNow
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting RabbitMQ status");
                return StatusCode(500, new { error = "Failed to get status" });
            }
        }

        /// <summary>
        /// 重新连接RabbitMQ
        /// </summary>
        [HttpPost("reconnect")]
        public async Task<ActionResult> Reconnect()
        {
            try
            {
                await _rabbitMQService.ReconnectAsync();
                return Ok(new { message = "Reconnected successfully", timestamp = DateTime.UtcNow });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error reconnecting to RabbitMQ");
                return StatusCode(500, new { error = "Failed to reconnect" });
            }
        }

        /// <summary>
        /// 发送测试用户事件消息
        /// </summary>
        [HttpPost("test/user-event")]
        public async Task<ActionResult> SendTestUserEvent([FromBody] TestUserEventRequest request)
        {
            try
            {
                var message = UserEventMessage.UserJoined(request.UserId, request.UserName);
                await _rabbitMQService.PublishUserEventAsync(message);

                return Ok(new 
                { 
                    message = "Test user event sent successfully", 
                    messageId = message.Id,
                    timestamp = DateTime.UtcNow 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending test user event");
                return StatusCode(500, new { error = "Failed to send test message" });
            }
        }

        /// <summary>
        /// 发送测试房间事件消息
        /// </summary>
        [HttpPost("test/room-event")]
        public async Task<ActionResult> SendTestRoomEvent([FromBody] TestRoomEventRequest request)
        {
            try
            {
                var message = RoomEventMessage.RoomCreated(request.RoomId, request.RoomName, request.MaxUsers);
                await _rabbitMQService.PublishRoomEventAsync(message);

                return Ok(new 
                { 
                    message = "Test room event sent successfully", 
                    messageId = message.Id,
                    timestamp = DateTime.UtcNow 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending test room event");
                return StatusCode(500, new { error = "Failed to send test message" });
            }
        }
    }

    public class TestUserEventRequest
    {
        public string UserId { get; set; } = string.Empty;
        public string UserName { get; set; } = string.Empty;
    }

    public class TestRoomEventRequest
    {
        public string RoomId { get; set; } = string.Empty;
        public string RoomName { get; set; } = string.Empty;
        public int MaxUsers { get; set; } = 10;
    }
} 